class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true;
    }
    GetFilterValue() {
        let item = {};
        item['HeaderId'] = parseInt(this.dataId);
        item['CurrentUserId'] = parseInt($("#UserId").val());
        item['WorkFlowId'] = $("#WorkFlowId").val() === '' ? 0 : parseInt($("#WorkFlowId").val());
        item['PageIndex'] = 1;
        item['Limit'] = parseInt($("#page-size_02").val());

        return item;
    }
    // 得到对账单数据
    GetEntityData() {
        let item = {};
        item['headerId'] = $("#HeaderId").val();
        item['billNo'] = $.trim($("#BillNo").val());                                  // 对账单号（自动生成）
        item['supplierId'] = $("#SupplierId").val();                                  // 供应商
        item['yearOfBill'] = $.trim($("#YearOfBill").val());                          // 年
        item['monthOfBill'] = $.trim($("#MonthOfBill").val());                        // 月
        item['tuckingCost'] = $.trim($("#TuckingCost").val());                        // 运费
        item['cycleOfBillFrom'] = $.trim($("#CycleOfBillFrom").val());                // 对账周期开始
        item['cycleOfBillTo'] = $.trim($("#CycleOfBillTo").val());                    // 对账周期结束
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#HeaderId").val(item.headerId);
        $("#BillNo").val(item.billNo);
        $("#SupplierId").val(item.supplierId);
        $("#SupplierName").val(item.supplierName);
        $("#YearOfBill").val(item.yearOfBill);
        $("#MonthOfBill").val(item.monthOfBill);
        $("#CycleOfBillFrom").val(item.cycleOfBillFrom);
        $("#CycleOfBillTo").val(item.cycleOfBillTo);
        $("#UpdatedByName").val(item.updatedByName);
        $("#UpdatedDate").val(formatNullData(item.updatedDate));
        $("#Description").val(item.description);
        // 最后的审核人、审核日期
        $("#CheckedBy").val(item.checkedBy);
        $("#CheckedByName").val(item.checkedByName);
        $("#CheckedDate").val(item.checkedDate === null ? '' : item.checkedDate);
        $("#CheckedStatus").val(item.checkedStatus);
        $('#FlowOrderNo').val(item.flowOrderNo);

        // 设置用于控制的用户ID
        this.privateUserId = item.updatedBy;

        $("#ChoiceSupplier").attr("onclick", "");                  // 不允许选择
        $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));   // 对账总金额

        // 显示明细数据
        _InstancePageLinesPoStockIn.BuildDataTable(data.LinesPoStockInList);
        _InstancePageLines.BuildDataTable(data.LinesData);

        this.currentTaskPrivileges = item.currentTaskPrivileges;
        this.nextTaskPrivileges = item.nextTaskPrivileges;
        this.unCheckFlag = item.unCheckFlag;
        this.SetPageElementStatus(this.HidePageElement, this.ShowPageElement, function () {
            _InstancePageLinesPoStockIn.AutoAdjustTableHeightForLines();
        });

        $("#BillNo").focus();
    }
    Save() {
        super.Save(function (data, _this) {
            if (data > 0) {
                if (parseInt(_this.pageStatus) === 1) {
                    $("#HeaderId").val(data);   // 设置刚才插入的记录ID
                    $("#Action").val(2);
                    _this.dataId = data;
                    _this.pageStatus = 2;
                    $("#ChoiceSupplier").attr("onclick", "");   // 不允许选择
                    $("#panelSlave").show();
                    $("#ButPrint").show();
                    $("#CheckedTip").removeClass().addClass("n2");
                    $("#CheckedTip").html("状态：未审核。");
                    $("#CheckedTip").show();
                }
            }
        });
    }
    New() {
        super.New();
        $("#HeaderId").val(0);
        $("#panelSlave").hide();
        // 设置初始默认值
        let _currentDate = new Date();
        $("#YearOfBill").val(_currentDate.getFullYear());
        $("#MonthOfBill").val(_currentDate.getMonth() + 1);
        $("#UpdatedDate").val(getCurrentDate());
        this.SetCycleOfBill();
        this.FetchNewBillNo();
        // 新增状态时允许更改款号
        let _event_onclick = '_InstancePageHeader.DoChoiceSupplier()';
        $("#ChoiceSupplier").attr("onclick", _event_onclick);

        $("#BillNo").focus();
    }
    FetchNewBillNo() {
        super.DoAjax(null, "/purchase/notes_payabled/header/fetchNewBillNo.html", function (data, $self) {
            $("#BillNo").val(data.BillNo);
        });
    }
    DoChoiceSupplier() {
        let _choice = new CommonChoice();
        let params = {};
        params['Flag'] = 0;
        params['CurrentUserId'] = null;
        params['NotInGroupId'] = null;
        _choice.DoChoiceSupplier(params, "选择供应商", (data) => {
            if (data) {
                // 判断是否数据发生了改变如果改变则设置改变标记
                if ($("#SupplierName").val() !== data[1]) {
                    $("#form_data").data("changed", true);
                }
                $("#SupplierId").val(data[0]);
                $("#SupplierName").val(data[1]);
            }
        });
    }
    // 设置对账周期
    SetCycleOfBill() {
        let _y = parseInt($("#YearOfBill").val());
        let _m = parseInt($("#MonthOfBill").val()) - 1;
        let firstDay = new Date(_y, _m, 1);
        let lastDay = new Date(_y, _m + 1, 0);
        $("#CycleOfBillFrom").val(firstDay.getFullYear() + "-" + ((firstDay.getMonth()) + 1) + "-" + firstDay.getDate());
        $("#CycleOfBillTo").val(lastDay.getFullYear() + "-" + ((lastDay.getMonth()) + 1) + "-" + lastDay.getDate());
    }
    // 导出到Excel
    DoExport() {
        //showModal(585, 285, '导出设置', parent.basePath + '/purchase/notes_payabled/export/setting.html', null, null);
        $("#exportExcel").attr("action", parent.basePath + "/purchase/notes_payabled/export.html");
        $("#Export_HeaderId").val($("#HeaderId").val());
        $("#Export_StyleNoFlag").val(5);  // 随便设置 只要大于 2 即可，目的为了避开这个参数
        $("#exportExcel").submit();
    }
    ShowPageElement() {
        $("Button.act__save").show();
        if (!$("span.act__delete").hasClass("act__delete")) {
            $("span.act__delete").addClass("trash");
            $("span.act__delete i").addClass("fa-all fa-trash-o fa-1");
        }
    }
    HidePageElement() {
        //$("Button.act__save").hide();
        //$("span.act__delete").removeClass("trash");
        //$("span.act__delete i").removeClass("fa-all fa-trash-o fa-1");
    }
    Expand() {
        super.Expand(function () {
            // 自适应高度
            _InstancePageLinesPoStockIn.AutoAdjustTableHeightForLines();
        });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () {
            // 自适应高度
            _InstancePageLinesPoStockIn.AutoAdjustTableHeightForLines();
        });
    }
}

//------------------------------------------------------------------------------
// 明细处理部分
//------------------------------------------------------------------------------
class MyPageLinesPoStockIn extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.orderby = "";
        this._choice_result = [];
    }
    // 根据条件搜索明细，flag: 0 显示全部 1 按条件搜索
    FetchLines(flag) {
        let _params = {};
        _params['HeaderId'] = parseInt($("#HeaderId").val());
        if (flag === 1) {
            _params['PoNoFilterValue'] = $.trim($("#PoNoFilterValue_02").val()) === "" ? null : $.trim($("#PoNoFilterValue_02").val());
            _params['StockInBillNoFilterValue'] = $.trim($("#StockInBillNoFilterValue_02").val()) === "" ? null : $.trim($("#StockInBillNoFilterValue_02").val());
        } else {
            $("#PoNoFilterValue_02").val("");
            $("#StockInBillNoFilterValue_02").val("");
        }

        super.DoAjax(_params, "/purchase/notes_payabled/lines/postockin/fetch.html", function (data, $self) {
            // 显示明细数据
            $self.BuildDataTable(data);
            if (data === null || data.length === 0) {
                ShowErrorMessagePanel('没有找到符合条件的数据。');
            }
        });
    }
    BuildDataTable(result) {
        $('#tabData11 tbody').empty();
        $('#tabData12 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            this.numCheckbox = 0;
            $("#panelSlave").show();
            // 自适应高度
            this.AutoAdjustTableHeightForLines();
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].linesId + '">';
            content_01 += '<td><label class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row_01" type="checkbox" onclick="_InstancePageLinesPoStockIn.DoCheckRow($(this), \'_check_row_01\', $(\'#check_all_po_stockin\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash act__delete" onclick="_InstancePageLinesPoStockIn.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].poTypeName) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].signedDate) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].orderArrivalDate) + '</td>';
            content_01 += '<td>' + result[i].purchasedByName + '</td>';
            content_01 += '<td>' + formatNullData(result[i].stockInBillNo) + '</td>';
            content_01 += '<td>' + formatNullData(result[i].arrivalDate) + '</td>';
            content_01 += '</tr>';

            content_02 += '<tr>';
            content_02 += '<td style="text-overflow:ellipsis;" title="' + formatNullData(result[i].styleNo) + '">' + formatNullData(result[i].styleNo) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].supplierName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].inspectedByName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].inspectedDate) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].stockInDate) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].updatedByName) + '</td>';
            content_02 += '<td>' + formatNullData(result[i].updatedDate) + '</td>';
            content_02 += '<td style="border-right:none;">' + formatNullData(result[i].description) + '</td>';
            content_02 += '</tr>';

            $('#tabData11 tbody').append(content_01);
            $('#tabData12 tbody').append(content_02);
            content_01 = '';
            content_02 = '';
        }
        // 设置明细部分高度
        this.AutoAdjustTableHeightForLines();
        setTwoTableRowColor("tabData11", "tabData12");
        $("#panelSlave").show();
    }
    DeleteLines($self) {
        let params = {};
        params['HeaderId'] = parseInt($("#HeaderId").val());
        params['LinesId'] = $self.parent().parent().attr("_mash_id");
        params['LinesData'] = "单据号：" + $("#BillNo").val() +
                "　订单合同号：" + $self.parent().parent().find("td").eq(2).text() +
                "　入库单号：" + $self.parent().parent().find("td").eq(7).text();
        params['DeletedBy'] = parseInt($("#UserId").val());
        params['PageIndex'] = 1;
        params['Limit'] = parseInt($("#page-size_02").val());

        super.DeleteLines(params, "/purchase/notes_payabled/lines/postockin/delete.html", (data, _this) => {
            // 订单到货对账明细
            _this.BuildDataTable(data.LinesPoStockInList);
            // 对账单明细
            _InstancePageLines.BuildDataTable(data.LinesData);
            // 设置总金额
            $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));
            ShowSuccessMessagePanel('删除引入的到货对账数据成功。');
        });
    }
    GetCheckedLinesData() {
        let _result = {};
        let itemList = [];
        if ($("input[type='checkbox'][name='_check_row_01']:checked").length > 0) {
            $("input[type='checkbox'][name='_check_row_01']:checked").each(function () {
                let $row = $(this).parent().parent().parent();
                let item = {};
                item['headerId'] = $("#HeaderId").val();
                item['linesId'] = $(this).val();
                item['updatedBy'] = $.trim($("#UserId").val());

                itemList.push(item);
            });
        }

        _result['DeletedLinesList'] = itemList;
        _result['HeaderId'] = parseInt($("#HeaderId").val());
        _result['BillNo'] = $("#BillNo").val();
        _result['DeletedBy'] = parseInt($("#UserId").val());
        _result['PageIndex'] = 1;
        _result['Limit02'] = parseInt($("#page-size_02").val());

        return JSON.stringify(_result);
    }
    BatchDeleteLines() {
        if ($("input[type='checkbox'][name='_check_row_01']:checked").length <= 0) {
            ShowErrorMessagePanel("请选择批量删除的记录。");
            return false;
        }
        super.BatchDeleteLines('/purchase/notes_payabled/lines/postockin/batchDelete.html', function (data, _this) {
            if (data.Success) {
                // 订单到货对账明细
                _this.BuildDataTable(data.LinesPoStockInList);
                // 对账单明细
                _InstancePageLines.BuildDataTable(data.LinesData);
                // 设置总金额
                $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));
                ShowSuccessMessagePanel('删除引入的到货对账数据成功。');
                $("#check_all_po_stockin").prop("checked", false);
            } else {
                ShowErrorMessagePanel("没有数据被删除。");
                $("#check_all_po_stockin").prop("checked", false);
            }
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').addClass("row__selected");
            // 设置删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, function ($row, index) {
            $('#tabData12 tbody tr:eq(' + index + ')').removeClass("row__selected");
            // 设置删除按钮有效
            let _event_delete_onclick = '_InstancePageLinesPoStockIn.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
    AutoAdjustTableHeightForLines() {
        let h = $(window).height();
        let _tabTop = $("#divH11").offset().top + 26;   // 用于随着窗口变化，下面明细高度随之变化的一个节点
        let _rc = Math.floor((h - _tabTop - 25) / 25);
        let _dh = _rc * 25 + 17;
        let _rowH = this.rows * 25 + 17; // 计算行高
        _dh = (_rowH >= _dh) ? _dh : _rowH;

        $("#divD11").css({"max-height": _dh - 17, height: _dh - 17});
        $("#divD12").css({"max-height": _dh + 1, height: _dh + 1});
    }
    ScrollTo() {
        $('#divH12').scrollLeft($('#divD12').scrollLeft());
        $('#divD11').scrollTop($('#divD12').scrollTop());
    }
    // 到货对账
    DoAccountPayable(flag) {
        let _choice = new CommonChoice();
        let _this = this;
        _choice.DoChoiceAccountPayable(flag, '订单到货对账', (data) => {
            if (data) {
                for (let i = 0; i < data.length; i++) {
                    _this._choice_result.push(parseInt(data[i]));
                }

                let item = {};
                item['HeaderId'] = parseInt($("#HeaderId").val());
                item['Flag'] = parseInt(flag);
                item['Limit'] = parseInt($("#page-size_02").val());        // limit;
                item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
                item['OrderBy'] = _this.orderby === '' ? null : _this.orderby;
                item['CreatedBy'] = parseInt($.trim($("#UserId").val()));
                item['UpdatedBy'] = parseInt($.trim($("#UserId").val()));
                item['StockInIdList'] = data;

                //保存，根据所选入库单，增加到货情况表和对账明细表记录
                super.DoAjax(item, "/purchase/notes_payabled/lines/postockin/add.html", (data, $self) => {
                    // 订单到货对账明细
                    $self.BuildDataTable(data.LinesPoStockInList);
                    // 对账单明细
                    _InstancePageLines.BuildDataTable(data.LinesData);
                    // 设置总金额
                    $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));
                    ShowSuccessMessagePanel('引入到货对账数据完成。');
                });
            }
        });
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
        this.selectedItemList = [];
        this.orderby = "";
    }
    SetPageSize02() {
        $.cookie("notes_payabled_lines_pagesize", $("#page-size_02").val());
        this.FetchLinesForPage(1);
    }
    // 获取明细表分页信息
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", pageIndex);
        }

        let item = {};
        item['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        item['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        item['Limit'] = parseInt($("#page-size_02").val());        // limit;
        item['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page"));
        item['OrderBy'] = this.orderby;

        return JSON.stringify(item);
    }
    FetchLinesForPageNoFilter() {
        $("#StyleNoFilterValue_02").val("");
        $("#MaterialNoFilterValue_02").val("");
        $("#MaterialNameFilterValue_02").val("");
        $("#MaterialColourNameFilterValue_02").val("");

        $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);
        this.FetchLinesForPage(1);
    }
    FetchLinesForPage(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/purchase/notes_payabled/lines/fetchLinesForPage.html",
            timeout: 60 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                $("#loading__indicator_02").show();
            }
        }).done((data) => {
            this.BuildDataTable(data);
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
            $("#loading__indicator_02").hide();
        });
    }
    BuildDataTable(result) {
        $('#tabData21 tbody').empty();
        $('#tabData22 tbody').empty();

        if (result.Success === false) {
            return;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar_02").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar_02").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar_02").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar_02").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar_02").data("swPagination").setPage(1);
        }

        // 得到数据列表
        result = result.DataList;
        if (result === null) {
            return false;
        }
        let content_01 = '';
        let content_02 = '';
        for (let i = 0; i < result.length; i++) {
            content_01 += '<tr _mash_id="' + result[i].linesId + '">';
            if (parseInt(result[i].rowFlag) === 1) {
                content_01 += '<td style="padding-left:3px;"><label class="btn" for="R-' + result[i].linesId + '"><input id="R-' + result[i].linesId + '" name="_check_row_02" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this), \'_check_row_02\', $(\'#check_all_lines\'));" value="' + result[i].linesId + '"/><i></i><span></span></label></td>';
                content_01 += '<td>' + formatNullData(result[i].poNo) + '</td>';
                content_01 += '<td>' + formatNullData(result[i].arrivalDate) + '</td>';
                content_01 += '<td>' + formatNullData(result[i].materialCode) + '</td>';
                this.rows = this.rows + 1;
                this.numCheckbox = this.numCheckbox + 1;
            } else {
                if (parseInt(result[i].rowFlag) === 2)
                    content_01 += '<td colspan="5" style="text-align:left; font-weight:bold; padding-left:20px;">小计数量</td>';
                if (parseInt(result[i].rowFlag) === 4)
                    content_01 += '<td colspan="5" style="text-align:left; font-weight:bold; padding-left:20px;">小计金额</td>';
                if (parseInt(result[i].rowFlag) === 3)
                    content_01 += '<td colspan="5" style="text-align:left; font-weight:bold; padding-left:20px;">' + result[i].materialName + '</td>';
            }
            if (parseInt(result[i].rowFlag) !== 2 || parseInt(result[i].rowFlag) !== 4) {
                content_01 += '<td>' + formatNullData(result[i].materialName) + '</td>';
            }
            content_01 += '</tr>';

            content_02 += '<tr>';
            if (parseInt(result[i].rowFlag) === 1) {
                content_02 += '<td >' + formatNullData(result[i].specification) + '</td>';
                content_02 += '<td style="text-align:right;">' + formatNullData(result[i].coefficient) + '</td>';
                content_02 += '<td>' + formatNullData(result[i].materialColourName) + '</td>';
                content_02 += '<td class="edited-cell">' + formatNullData(result[i].lotNo) + '</td>';                      // 缸号
                content_02 += '<td style="text-align:center;">' + formatNullData(result[i].uomName) + '</td>';
                content_02 += '<td style="text-align:right;">' + formatNullData(result[i].poQuantity) + '</td>';           // 订单数
                content_02 += '<td style="text-align:right;">' + formatNullData(result[i].stockInQuantity) + '</td>';      // 入库数
                content_02 += '<td style="text-align:right;" class="edited-cell">' + formatNullData(result[i].payabledQuantity) + '</td>';     // 对账数
                let _price01 = result[i].unitPriceAddedTax === null ? '' : result[i].unitPriceAddedTax.toFixed(4);
                content_02 += '<td style="text-align:right;">' + _price01 + '</td>';                                       // 含税单价
                let _price02 = result[i].unitPriceExcludedTax === null ? '' : result[i].unitPriceExcludedTax.toFixed(4);
                content_02 += '<td class="edited-cell" style="text-align:right;">' + _price02 + '</td>';                   // 不含税单价
            } else {
                if (parseInt(result[i].rowFlag) === 2) {
                    content_02 += '<td colspan="5"></td>';
                    content_02 += '<td></td>';                                                                             // 订单数
                    content_02 += '<td style="text-align:right; font-weight:bold; ">' + formatNullData(result[i].stockInQuantity) + '</td>';  // 入库数
                    content_02 += '<td style="text-align:right; font-weight:bold; ">' + formatNullData(result[i].payabledQuantity) + '</td>'; // 对账数
                    content_02 += '<td colspan="7" style="text-align:center; border-right:none;"></td>';
                } else {
                    content_02 += '<td colspan="10" style="text-align:center; border-right:none;"></td>';
                }
            }
            if (parseInt(result[i].rowFlag) !== 2) {
                if (parseInt(result[i].rowFlag) === 1) {
                    content_02 += '<td class="edited-cell" style="text-align:right;">' + result[i].payabledAmount.toFixed(2) + '</td>';    // 结算金额
                    content_02 += '<td class="edited-cell">' + formatNullData(result[i].invoiceNo) + '</td>';                              // 发票号
                    content_02 += '<td class="edited-cell" style="text-align:right;">' + formatNullData(result[i].taxRate) + '</td>';      // 税率                    
                    //let _tmp = result[i].invoiceDate === null ? '' : result[i].invoiceDate.substring(0, result[i].invoiceDate.length - 3).replace(/\-/g, "、");
                    content_02 += '<td style="text-align:center;" class="edited-cell">' + formatNullData(result[i].invoiceDate) + '</td>'; // 发票日
                    content_02 += '<td class="edited-cell" style="border-right:none;">' + formatNullData(result[i].description) + '</td>'; // 备注
                } else {
                    content_02 += '<td style="text-align:right; font-weight:bold; ">' + result[i].payabledAmount.toFixed(2) + '</td>';    // 结算金额
                    if (parseInt(result[i].rowFlag) === 4)
                        content_02 += '<td colspan="4" style="text-align:center; border-right:none;"></td>';
                    if (parseInt(result[i].rowFlag) === 3) {
                        content_02 += '<td>' + formatNullData(result[i].invoiceNo) + '</td>';
                        content_02 += '<td style="text-align:right;">' + formatNullData(result[i].taxRate) + '</td>';
                        content_02 += '<td colspan="2" style="text-align:center; border-right:none;"></td>';
                    }
                }
            }
            content_02 += '</tr>';

            $("#tabData21 tbody").append(content_01);
            $("#tabData22 tbody").append(content_02);
            content_01 = '';
            content_02 = '';
        }
        setTwoTableRowColor("tabData21", "tabData22");
        //$(window).resize();               // 防止因为出现滚动条而造成画面显示问题

        let cell_id = "_cell__field";
        let cell_name = "__cell__field";
        let _this = this;
        $('#tabData22 tbody tr').find("td.edited-cell").click(function () {
            switch ($(this).index()) {
                case 7:  // 对账数量
                    OnCellClickEvent($(this), cell_id, cell_name, 0, ($input) => {
                        _this.SetPayedQuntity($(this));
                    });
                    break;
                case 13:
                    OnCellDateEditEvent($(this), cell_id, cell_name, 'yyyy、MM');
                    break;
                default:
                    OnCellClickEvent($(this), cell_id, cell_name, 0);
                    break;
            }
        });
        this.ResetSelectRowStatus();
    }
    // 设置对账数
    SetPayedQuntity($td) {
        let _unitprice = parseFloat($td.parent().find('td').eq(8).text());
        let _payedQuntity = $.trim($td.children("input").val()) === "" ? 0 : parseFloat($.trim($td.children("input").val()));
        let _amount = _unitprice * _payedQuntity;
        $td.parent().find('td').eq(10).text(_amount.toFixed(2));
    }
    // 得到要保存的数据
    GetLinesData() {
        let _itemList = [];
        $('#tabData22 tbody').find("tr").each(function () {
            let row = $(this).index();
            let $tr2 = $(this);
            let $tr1 = $('#tabData21 tbody').find("tr").eq(row);
            if ($(this).find('td.dirty').length > 0) {
                let item = {};
                item['linesId'] = $tr1.attr("_mash_id");
                item['lotNo'] = formatNullInputValue($.trim($tr2.find('td').eq(3).text()));
                item['payabledQuantity'] = formatNullInputValue($.trim($tr2.find('td').eq(7).text())) === null ? 0 : $.trim($tr2.find('td').eq(7).text());  //  对账数量
                item['unitPriceExcludedTax'] = formatNullInputValue($.trim($tr2.find('td').eq(9).text()));      // 不含税单价
                if ($tr2.find('td').eq(10).hasClass("dirty")) {
                    item['payabledAmount'] = formatNullInputValue($.trim($tr2.find('td').eq(10).text()));           // 结算金额
                } else {
                    item['payabledAmount'] = (parseFloat(item['payabledQuantity']) * parseFloat($.trim($tr2.find('td').eq(8).text()))).toFixed(2);
                    $tr2.find('td').eq(10).text(item['payabledAmount']);
                    console.info(item['payabledAmount']);
                }
                item['invoiceNo'] = formatNullInputValue($.trim($tr2.find('td').eq(11).text()));                // 发票号
                item['taxRate'] = formatNullInputValue($.trim($tr2.find('td').eq(12).text()));                  // 税率
                if ($.trim($tr2.find('td').eq(13).text()) === '') {
                    item['invoiceDate'] = null;
                } else {
                    //let _invoiceDate = '';
                    //let _tmpArr = $.trim($tr2.find('td').eq(13).text()).split("、");
                    //_invoiceDate = _tmpArr[0] + '-' + _tmpArr[1] + '-01';
                    item['invoiceDate'] = $.trim($tr2.find('td').eq(13).text()); //_invoiceDate;                // 开票日
                }
                item['description'] = $.trim($tr2.find('td').eq(14).text());                                    // 备注
                item['updatedBy'] = $("#UserId").val();
                _itemList.push(item);
            }
        });

        let _result = {};
        _result['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        _result['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        _result['Limit'] = parseInt($("#page-size_02").val());        // limit;
        _result['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        _result['OrderBy'] = this.orderby;
        _result['ItemList'] = _itemList;

        return JSON.stringify(_result);
    }
    SaveLines() {
        //step 1、进行页面验证，失败则返回
        let _success = CheckGridInput();
        if (!_success)
            return;

        super.SaveLines("/purchase/notes_payabled/lines/update.html", (data, _this) => {
            _this.selectedItemList = [];
            // 刷新合同明细
            _this.BuildDataTable(data.LinesData);
            // 设置总金额
            $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));
            ShowSuccessMessagePanel("保存成功。");
        });
    }
    SyncLinesData() {
        //if (Object.keys(this.selectedItemList).length === 0) {
        //    ShowErrorMessagePanel("请选择要同步的数据。");
        //    return false;
        //}
        showModal(795, 358, '同步对账数据', parent.basePath + '/purchase/notes_payabled/lines/sync.html', null, ($dialog) => {
            parent.arrChoice.splice(0, parent.arrChoice.length);
            parent.choice_success = false;
        });
    }
    OnSyncLinesData(invoiceNo, invoiceDate, taxRate) {
        let _result = {};
        let arrItem = [];
        if (Object.keys(this.selectedItemList).length > 0) {
            for (let i = 0; i < Object.keys(this.selectedItemList).length; i++) {
                let item = {};
                item['linesId'] = Object.keys(this.selectedItemList)[i];
                item['updatedBy'] = $.trim($("#UserId").val());
                item['invoiceNo'] = invoiceNo === '' ? null : invoiceNo;        // 用于同步发票号
                item['invoiceDate'] = invoiceDate === '' ? null : invoiceDate;  // 用于同步开票日
                item['taxRate'] = taxRate === '' ? null : taxRate;              // 用于同步税率
                arrItem.push(item);
            }
        } else {
            let item = {};
            item['headerId'] = $("#HeaderId").val();
            item['linesId'] = null;
            item['updatedBy'] = $.trim($("#UserId").val());
            item['invoiceNo'] = invoiceNo === '' ? null : invoiceNo;        // 用于同步发票号
            item['invoiceDate'] = invoiceDate === '' ? null : invoiceDate;  // 用于同步开票日
            item['taxRate'] = taxRate === '' ? null : taxRate;              // 用于同步税率
            arrItem.push(item);
        }

        _result['HeaderId'] = parseInt($.trim($("#HeaderId").val()));
        _result['CurrentUserId'] = parseInt($("#UserId").val());      // 当前操作者，用于过滤供应商分组
        _result['Limit'] = parseInt($("#page-size_02").val());        // limit;
        _result['PageIndex'] = parseInt($("#page_indicator_block_02").attr("_msh_page"));
        _result['OrderBy'] = this.orderby;
        _result['ItemList'] = arrItem;

        super.DoAjax(_result, "/purchase/notes_payabled/lines/update.html", function (data, $self) {
            $("#check_all_lines").prop("checked", false);
            $self.selectedItemList = [];
            // 刷新合同明细
            $self.BuildDataTable(data.LinesData);
            // 设置总金额
            $("#TotalAmount").val(formatMoney(data.TotalAmount, 1));
            ShowSuccessMessagePanel("数据同步完成。");
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        let key = $self.val();
        let $row = $self.parent().parent().parent();
        let rowIndex = $row.index();
        if ($self.is(":checked") === true) {
            $row.addClass("row__selected");
            $('#tabData22 tbody tr:eq(' + rowIndex + ')').addClass("row__selected");
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", "");
            let item = {};
            // 为翻页选择做准备
            item["linesId"] = key;
            this.selectedItemList[key] = item;
        } else {
            $row.removeClass("row__selected");
            $('#tabData22 tbody tr:eq(' + rowIndex + ')').removeClass("row__selected");
            // 设置删除按钮有效
            var _event_delete_onclick = "_InstancePageLines.DoDelete($(this))";
            $row.children('td').eq(2).children('span').eq(0).attr("onclick", _event_delete_onclick);
            delete this.selectedItemList[key];
        }
    }
    // 每次翻页都恢复选定结果
    ResetSelectRowStatus() {
        let _this = this;
        $("#tabData21 tbody").find("tr").each(function (index) {
            let key = $(this).attr("_mash_id");
            if (_this.selectedItemList[key] !== undefined) {
                $(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row_02']").eq(0).prop('checked', true);
                $(this).addClass("row__selected");
                $('#tabData22 tbody tr:eq(' + index + ')').addClass("row__selected");
            }
        });
        // 设置选择全部的状态
        let n = $("input[type='checkbox'][name='_check_row_02']:checked").length;
        if (n < $("#tabData21 tbody").find("tr").length || n === 0) {
            $("#check_all_lines").prop("checked", false);
        } else {
            $("#check_all_lines").prop("checked", true);
        }
    }
    ScrollTo() {
        $('#divH22').scrollLeft($('#divD22').scrollLeft());
        $('#divD21').scrollTop($('#divD22').scrollTop());
    }
    SortTable(order_by) {
        this.orderby = order_by + ", P.StyleNo, L.UpdatedDate DESC";
        this.FetchLinesForPage(1);
    }
}

var _InstancePageHeader = null;
var _InstancePageLinesPoStockIn = null;
var _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#HeaderId").val();

    let notes_payabled_list_result = $.cookie("notes_payabled_list_result") === undefined ? "" : $.cookie("notes_payabled_list_result");
    let _pageListData = [];
    if (notes_payabled_list_result !== "") {
        _pageListData = notes_payabled_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/purchase/notes_payabled/list.html",
            "/purchase/notes_payabled/header/fetchByKey.html",
            "/purchase/notes_payabled/header/save.html",
            "/purchase/notes_payabled/header/export.html",
            "/purchase/notes_payabled/header/print.html");

    _InstancePageLinesPoStockIn = new MyPageLinesPoStockIn();
    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelData"});

    window.laydate.render({
        elem: '#CycleOfBillFrom',
        theme: '#393D49',
        trigger: 'click'
    });
    window.laydate.render({
        elem: '#CycleOfBillTo',
        theme: '#393D49',
        trigger: 'click'
    });
    // 发票日
    window.laydate.render({
        elem: '#InvoiceDate',
        format: 'yyyy、MM',
        theme: '#393D49',
        trigger: 'click'
    });

    $("#loading__indicator_02").hide();

    // 设置明细分页控制
    $("#wrapper__navbar_02").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", page);
            _InstancePageLines.FetchLinesForPage(page);
        }
    });
    $("abbr.page_indicator_block,#wrapper__navbar_02").attr("_msh_page", 1);

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    SetSearchWnd();

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
    let w = $(window).width();
    let wLeft = 817;
    $("#divH12").css({width: w - wLeft - 17});
    $("#divD12").css({left: -1, width: w - wLeft - 16});
    wLeft = 677;
    $("#divH22").css({width: w - wLeft - 17});
    $("#divD22").css({left: -1, width: w - wLeft - 16});

    if (_InstancePageLinesPoStockIn !== null)
        _InstancePageLinesPoStockIn.AutoAdjustTableHeightForLines();
}

function SetSearchWnd() {
    $("div.search").unbind('keyup');

    let clazz = 'search--active';
    // 对订单到货情况进行搜索的搜索
    let $search_02 = $('#search_02');
    // 搜索按钮
    $('#search_btn_02').on('click', function (event) {
        $search_02.addClass(clazz);
        $search_02.on(window.transitionProp, function (event) {
            $search_02.find('input').first().focus();
        });
    });
    // 搜索窗口关闭
    $('#search__form_butclose_02').on('click', function (event) {
        $search_02.removeClass(clazz);
    });
    // 搜索框回车直接进行搜索
    $("#search_02").bind('keyup', function (e) {
        let key = e.keyCode;
        if (key === 13) {
            $("#but_filter_02").click();
        }
    });
}
//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _BillNo: "required",
            _DateOfDelivery: {
                dateISO: true,
                required: true
            },
            _SupplierName: "required"
        },
        messages: {
            _BillNo: "请填写对账单号。",
            _SupplierName: "请填写供应商。"
        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});

// 验证输入
function CheckGridInput() {
    $('#tabData22 tbody').find("tr").each(function (index) {
        let $tr2 = $('#tabData22 tbody').find("tr").eq(index);
        let _payabledQuantity = $.trim($tr2.find('td').eq(7).text()) === '' ? 0 : $.trim($tr2.find('td').eq(7).text());     // 对账数量
        let _unitpriceExcludedTax = $.trim($tr2.find('td').eq(9).text()) === '' ? 0 : $.trim($tr2.find('td').eq(9).text()); // 不含税单价
        let _payabledAmount = $.trim($tr2.find('td').eq(10).text()) === '' ? 0 : $.trim($tr2.find('td').eq(10).text());     // 结算金额

        if (_payabledQuantity !== 0) {
            if (!isNumber(_payabledQuantity)) {
                GridCheckErrHandle($tr2, 7, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 7);
            }
        }
        if (_unitpriceExcludedTax !== 0) {
            if (!isNumber(_unitpriceExcludedTax)) {
                GridCheckErrHandle($tr2, 9, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 9);
            }
        }
        if (_payabledAmount !== 0) {
            if (!isNumber(_payabledAmount)) {
                GridCheckErrHandle($tr2, 10, '请输入正确的数字。');
            } else {
                GridCheckSuccessHandle($tr2, 10);
            }
        }
    });
    if ($('#tabData21 tbody').find('td.error').length > 0 || $('#tabData22 tbody').find('td.error').length > 0) {
        ShowErrorMessagePanel('对不起，填写的数据有错误。');
        return false;
    } else {
        return true;
    }
}
function GridCheckErrHandle($row, index, errMsg) {
    $row.find('td').eq(index).addClass("error");
    $row.find('td').eq(index).attr('title', errMsg);
}
function GridCheckSuccessHandle($row, index) {
    $row.find('td').eq(index).removeClass("error");
    $row.find('td').eq(index).attr('title', '');
}